package com.ruitu.health_1.ui;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.hjq.permissions.Permission;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.health_1.R;
import com.ruitu.health_1.mvp.model.UserInfoModel;
import com.ruitu.health_1.mvp.presenter.UserInfoPresent;
import com.ruitu.health_1.view.GlideImageLoader;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.util.PermissionUtil;
import com.ruitu.router_module.util.ReqUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MultipartBody;

import static com.lzy.imagepicker.ImagePicker.RESULT_CODE_BACK;
import static com.lzy.imagepicker.ImagePicker.RESULT_CODE_ITEMS;

public class PersonalCenterActivity extends BaseActivity<UserInfoPresent.ChangeHeadImgP, UserInfoModel.ChangeHeadImgM> {

    private TextView tv_user_name, tv_sex, tv_birthday;
    //头像
    private ImageView iv_header;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_personal_center;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setHeadTitle("用户信息");
        initImagePicker();
        tv_user_name = findViewById(R.id.tv_user_name);
        tv_sex = findViewById(R.id.tv_sex);
        tv_birthday = findViewById(R.id.tv_birthday);
        iv_header = findViewById(R.id.iv_header);
        setOnClickListener(iv_header);
        initDate();
    }

    public void setHeadSuc() {
        initHeader();
        onRe();
    }

    public void onRe() {
        Arad.bus.post(2020031000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CODE_ITEMS) {
            if (data != null) {
                ArrayList<ImageItem> imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                headPath = imageItems.get(0).path;
                showProgress();
                MultipartBody body = p.changeHeadImg(new File(headPath), AppHolder.instance().getUser().getId());
                p.changeHeadImg(body);
            }
        } else if (requestCode == RESULT_CODE_BACK) {

        }
    }

    private Map<String, String> map;

    private void changeInfo() {
        map = new HashMap<>();
        map.put("id", AppHolder.instance().getUser().getId());
        map.put("gender", gender);
        map.put("birthday", birth);
        showProgress();
        p.changeUserInfo(ReqUtil.getBody(map, true));
    }

    private String headPath;

    //初始化用户信息
    private void initDate() {
        tv_user_name.setText(AppHolder.instance().getUser().getUsername());
        tv_sex.setText(TextUtils.equals(AppHolder.instance().getUser().getGender(), "1") ? "女" : "男");
        tv_birthday.setText(AppHolder.instance().getUser().getBirthday());
        headPath = AppHolder.instance().getUser().getIcon();
        initHeader();
//        tv_user_name.setText(AppHolder.instance().getUser().getUserName());
//        tv_version.setText(AppUtils.getAppVersionCode() + "");
    }

    public void setSex() {
        if (!TextUtils.isEmpty(gender)) {
            tv_sex.setText(TextUtils.equals(gender, "1") ? "女" : "男");
        }
        if (!TextUtils.isEmpty(birth)) {
            tv_birthday.setText(birth);
        }
        onRe();
    }

    private void initHeader() {
        Glide.with(this).load("http://" + headPath).apply(Arad.opts_circle).into(iv_header);
    }

    //获取本地头像
    public void onHeaderIma(View view) {
        PermissionUtil.handleMultiPermission(this, "读写手机存储", new PermissionUtil.PermissionListener() {
            @Override
            public void onPermissionOk(boolean isOk) {
                if (isOk) {
                    Intent intent = new Intent(PersonalCenterActivity.this, ImageGridActivity.class);
                    startActivityForResult(intent, RESULT_CODE_ITEMS);
                }
            }

            @Override
            public void onOpenPermissionPage(boolean isOpen) {

            }
        }, Permission.Group.STORAGE);

    }

    public void onSex(View v) {
        DialogSex();
    }

    String birth;
    String gender;

    public void onBirthday(View view) {
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                birth = year + "年" + month + "月" + dayOfMonth + "日";
                changeInfo();
            }
        }, 2000, 1, 1);
        dialog.show();
    }

    public void onAddress(View view) {
        startActivity(AddressActivity.class);
    }

    public void onLoginOut(View view) {
        Arad.preferences.putString("token", "").flush();
        Arad.bus.post(new EventModel(19110400, null));
        finish();
    }

    public void onUserName(View view) {

    }

    private PopupWindow popupWindow;
    private AlertDialog dialog;

    private void DialogSex() {
        dialog = new AlertDialog.Builder(this, R.style.CommonBottomDialogStyle).create();
        View view = View.inflate(this, R.layout.item_sex_pop, null);
        dialog.setView(view);

        view.findViewById(R.id.tv_man).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gender = "1";
                changeInfo();
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.tv_woman).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gender = "2";
                changeInfo();
                dialog.dismiss();
            }
        });
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 初始化图片选择器
     */
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(1);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

}
